package com.example.fileupload.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
 * @author liaofengshun
 */
@Slf4j
@Controller
@RequestMapping("/upload_controller")
public class UploadController {
    private static final String FILE_UPLOAD_PATH="E:\\tmp\\";
    @RequestMapping("/upload_with_io")
    public String singleFileUpload(@RequestParam(value = "file",required = false) MultipartFile file, Model model){
        if (file.isEmpty()){
            model.addAttribute("message","file is empty");
            log.info("file is empty");
            return "uploadStatus";
        }
        try{
            /** File(文件所在路径，文件目录) */
            File rootPath=new File(FILE_UPLOAD_PATH,file.getOriginalFilename());
            FileOutputStream fos=new FileOutputStream(rootPath);
            byte[] byteFile=file.getBytes();
            fos.write(byteFile);
            fos.flush();
            fos.close();
            log.info("upload success");
            model.addAttribute("message","file is in"+rootPath);

        } catch (IOException e) {
            log.error("upload error { }",e);
        }
        return "uploadStatus";
    }
    @RequestMapping("/upload_by_nio")
    public String singleFileUploadByNio(@RequestParam(value ="file",required = false) MultipartFile file,Model model){
        if(file.isEmpty()){
            log.info("file is empty");
            model.addAttribute("message","file is empty");
            return "uploadStatus";
        }
        try{
            Path rootPath = Paths.get(FILE_UPLOAD_PATH);
            Path filePath = Paths.get(FILE_UPLOAD_PATH+file.getOriginalFilename());
            byte[] bytes = file.getBytes();
            if (Files.exists(filePath)){
                Files.delete(filePath);
            }
            Files.write(filePath,bytes);
            model.addAttribute("message","upload to"+filePath);


        } catch (IOException e) {
            log.error("upload error { }",e);
        }
        return "uploadStatus";
    }
    @RequestMapping("/upload_by_transfer_to")
    public String uploadByTransferTo(@RequestParam(value = "file",required = false)MultipartFile file,Model model){
        try {
            file.transferTo(new File(FILE_UPLOAD_PATH + file.getOriginalFilename()));
            log.info("upload success");
            model.addAttribute("message","file is in"+FILE_UPLOAD_PATH+file.getOriginalFilename());
        } catch (IOException e) {
            model.addAttribute("message","upload failed");
            log.error("upload error,{ }",e);
        }
        return "uploadStatus";
    }


    /**
     * 上传多个文件到指定路径
     * FILE_UPLOAD_PATH E:\tmp\
     * 遍历文件时，创建StringBuilder来构建一个新的文件名
     * subString(int begin)截取文件后缀名
     * getName()获得的是服务器上文件的名字
     * getOriginalFilename()获取的是客户端文件名字
     * @param files
     * @param model
     * @return
     */
    @RequestMapping(value = "/upload_files")
    public String uploadFiles(@RequestParam(value = "files",required = false) MultipartFile[] files,Model model){
        log.info("文件的数量{}",files.length);
        for (MultipartFile file : files) {
            StringBuilder filename=new StringBuilder(FILE_UPLOAD_PATH).append("pic-").append(System.currentTimeMillis());
            try{
                String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
                filename.append(suffix);
                file.transferTo(new File(filename.toString()));
                log.info("文件名称{}",filename.toString());
            } catch (Exception e) {
                log.error("上传出错{}",e);
                model.addAttribute("message","上传失败");
                return "uploadStatus";
            }
        }
        model.addAttribute("message","上传完成");
        return "uploadStatus";
    }
}
